/**
 * 您可以将常用的方法、或系统 API，统一封装，暴露全局，以便各页面、组件调用，而无需 require / import.
 */
const prompt = require('@system.prompt')
const storage = require('@system.storage')

/**
 * 拼接 url 和参数
 */
function queryString(url, query) {
  let str = []
  for (let key in query) {
    str.push(key + '=' + query[key])
  }
  let paramStr = str.join('&')
  return paramStr ? `${url}?${paramStr}` : url
}

function showToast(message = '', duration = 0) {
  if (!message) return
  prompt.showToast({
    message: message,
    duration
  })
}

function setStorage(key, value) {
  // 设置storage
  console.info("设置storage key =>", key)
  storage.set({
    key,
    value: value,
    fail(data, code) {
      console.log(`setStorage fail, code = ${code}`)
    }
  })
}

function getStorage(key) {
  return new Promise((resolve, reject) => {
    // 获取storage
    storage.get({
      key,
      success(data) {
        if (data) {
          resolve(data)
        } else {
          resolve('')
        }
      },
      fail(data, code) {
        console.log(`getStorage fail, code = ${code}`)
        reject({ data, code })
      }
    })
  })
}


// 生成随机字符
function generateRandomString(length = 12) {
  const chars = 'abcdefghijklmnopqrstuvwxyz0123456789'; // 小写字母和数字
  let result = '';
  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * chars.length); // 生成随机索引
    result += chars[randomIndex]; // 添加对应字符到结果中
  }
  return result;
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}


// 格式化时间
const formatDate = (timestamp, formatStr = 'YYYY-MM-dd HH:mm:ss') => {
  let date = new Date(timestamp)
  let year = date.getFullYear(),
    month = formatNumber(formatNumber(date.getMonth() + 1)), // 月份是从0开始的
    day = formatNumber(date.getDate()),
    hour = formatNumber(date.getHours()),
    min_hour = formatNumber(date.getHours()),
    min = formatNumber(date.getMinutes()),
    sec = formatNumber(date.getSeconds()),
    formater = formatStr.replace('YYYY', year)
      .replace('MM', month)
      .replace('dd', day)
      .replace('HH', hour)
      .replace('hh', date.getHours())
      .replace('mm', min)
      .replace('ss', sec);
  // console.log("formater =>", formater)
  return formater
}
export default {
  showToast,
  queryString,
  setStorage,
  getStorage,
  generateRandomString,
  formatDate
}
